package com.unis.service.system.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.unis.common.util.TemplateUtil;
import com.unis.dto.ResultDto;
import com.unis.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import tk.mybatis.mapper.entity.Example;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unis.mapper.system.PermissionMapper;
import com.unis.model.system.Permission;
import com.unis.service.system.PermissionService;
import com.unis.common.exception.app.AppRuntimeException;

/**
 * <pre>
 * @see PermissionService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2018-12-28
 */
@Service("permissionService")
public class PermissionServiceImpl extends BaseServiceImpl implements PermissionService {
	private static final Logger logger = LoggerFactory.getLogger(PermissionServiceImpl.class);
    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * @see PermissionService#insert(Permission permission)
     */
    @Override
    public int insert(Permission permission) throws Exception {
    	if (permission!=null){
	        permission.setPk(TemplateUtil.genUUID());
	        return permissionMapper.insertSelective(permission);
    	}else{
    		logger.error("PermissionServiceImpl.insert时permission数据为空。");
    		throw new AppRuntimeException("PermissionServiceImpl.insert时permission数据为空。");
    	}        
    }

    /**
     * @see PermissionService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("PermissionServiceImpl.delete时pk为空。");
    		throw new AppRuntimeException("PermissionServiceImpl.delete时pk为空。");
    	}else{
    		return permissionMapper.deleteByPrimaryKey(pk);
    	}
    }

    /**
     * @see PermissionService#updateByPrimaryKey(Permission permission)
     */
    @Override
    public int updateByPrimaryKey(Permission permission) throws Exception {
        if (permission!=null){
        	if(StringUtils.isBlank(permission.getPk())){
        		logger.error("PermissionServiceImpl.updateByPrimaryKey时permission.Pk为空。");
        		throw new AppRuntimeException("PermissionServiceImpl.updateByPrimaryKey时permission.Pk为空。");
        	}
	        return permissionMapper.updateByPrimaryKeySelective(permission);
    	}else{
    		logger.error("PermissionServiceImpl.updateByPrimaryKey时permission数据为空。");
    		throw new AppRuntimeException("PermissionServiceImpl.updateByPrimaryKey时permission数据为空。");
    	}
    }
    /**
     * @see PermissionService#queryPermissionByPrimaryKey(String pk)
     */
    @Override
    public Permission queryPermissionByPrimaryKey(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("PermissionServiceImpl.queryPermissionByPrimaryKey时pk为空。");
    		throw new AppRuntimeException("PermissionServiceImpl.queryPermissionByPrimaryKey时pk为空。");
    	}else{
    		return permissionMapper.selectByPrimaryKey(pk);
    	}
    }
    
    
    /**
     * @see PermissionService#queryAsObject(Permission permission)
     */
    @Override
    public Permission queryAsObject(Permission permission) throws Exception {
        if (permission!=null){
	        return permissionMapper.selectOne(permission);
    	}else{
    		logger.error("PermissionServiceImpl.queryAsObject时permission数据为空。");
    		throw new AppRuntimeException("PermissionServiceImpl.queryAsObject时permission数据为空。");
    	}
    }
    
    /**
     * @see PermissionService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
    	if(example!=null){
    		return permissionMapper.selectCountByExample(example);
    	}else{
    		logger.error("PermissionServiceImpl.queryCountByExample时example数据为空。");
    		throw new AppRuntimeException("PermissionServiceImpl.queryCountByExample时example数据为空。");
    	}
    }
    /**
     * @see PermissionService#queryListByExample(Example example)
     */
    @Override
    public List<Permission> queryListByExample(Example example) throws Exception {
    	if(example!=null){
    		return permissionMapper.selectByExample(example);
    	}else{
    		logger.error("PermissionServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("PermissionServiceImpl.queryListByExample时example数据为空。");
    	}
    }
    /**
     * @see PermissionService#queryPageInfoByExample(Example example,int pageNum,int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example,int pageNum,int pageSize) throws Exception {    	
    	if(example!=null){
    		PageHelper.startPage(pageNum,pageSize);
    		return new PageInfo(permissionMapper.selectByExample(example));
    	}else{
    		logger.error("PermissionServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("PermissionServiceImpl.queryListByExample时example数据为空。");
    	}    	
    }
	/**
	 * @see PermissionService#queryCurrentUserPermit(String userId)
	 */
	@Override
	public List<Permission> queryCurrentUserPermit(String userId) throws Exception {
		if(StringUtils.isNotBlank(userId)){
			return permissionMapper.queryCurrentUserPermit(userId);
		}else{
			logger.error("RoleServiceImpl.queryCurrentUserPermit时userId数据为空。");
			throw new AppRuntimeException("RoleServiceImpl.queryCurrentUserPermit时userId数据为空。");
		}
	}
	/**
	 * @see PermissionService#queryListByPage(Map parmMap,int pageNum,int pageSize)
	 */
	@Override
	public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws  Exception{
		if (parmMap!=null){
			Example example = new Example(Permission.class);
			//example.setOrderByClause("rksj DESC,pk asc");设置排序
			Example.Criteria criteria = example.createCriteria();
			//criteria设置
			// = --> andEqualTo(field,value)
			// like --> andLike(field,likeValue)；likeValue 包含‘%’
			// is null --> andIsNull(field)
			// is not null --> andIsNotNull(field)
			// <> --> andNotEqualTo(field)
			// > --> andGreaterThan(field,value)
			// >= --> andGreaterThanOrEqualTo(field,value)
			// < --> andLessThan(field,value)
			// <= --> andLessThanOrEqualTo(field,value)
			// in --> andIn(field,Iterable value)
			// not in --> andNotIn(field,Iterable value)
			// between --> andBetween(field,beginValue,endValue)
			// not like --> andNotLike(field,likeValue)；likeValue 包含‘%’

			// or --> 上述方法的and 都有与之对应的or方法 eg: orEqualTo(field,value)

			//criteria.andEqualTo("yxx",1);设置yxx=1
			/**
			 *此方法请根据需要修改下方条件
			 */
			//此查询仅针对单表查询，若需要多表查询，尽量使用配置Mapper.xml 和Mapper.java的方式
			//生成条件中均为 and field = value
			//生成代码中，若表结构中有_等字符，生成字段可能会与实体类不同，请注意修改
			if(parmMap.get("pk")!=null && StringUtils.isNotBlank(parmMap.get("pk").toString())){
				criteria.andEqualTo("pk",parmMap.get("pk").toString().trim());
			}
			if(parmMap.get("code")!=null && StringUtils.isNotBlank(parmMap.get("code").toString())){
				criteria.andEqualTo("code",parmMap.get("code").toString().trim());
			}
			if(parmMap.get("name")!=null && StringUtils.isNotBlank(parmMap.get("name").toString())){
				criteria.andLike("name","%"+parmMap.get("name").toString().trim()+"%");
			}
			if(parmMap.get("comments")!=null && StringUtils.isNotBlank(parmMap.get("comments").toString())){
				criteria.andEqualTo("comments",parmMap.get("comments").toString().trim());
			}
			PageInfo pageInfo = this.queryPageInfoByExample(example,pageNum,pageSize);
			ResultDto result = new ResultDto();
			result.setRows(pageInfo.getList());
			result.setPage(pageInfo.getPageNum());
			//result.setTotal(pageInfo.getPages());
			result.setTotal((int)pageInfo.getTotal());
			return result;
		}else{
			logger.error("PermissionServiceImpl.queryListByPage时parmMap数据为空。");
			throw new AppRuntimeException("PermissionServiceImpl.queryListByPage时parmMap数据为空。");
		}
	}

	/**
	 * @see PermissionService#queryListByType(String ,String,String)
	 * @param cType
	 * @param foreingKey
	 * @return
	 * @throws Exception
	 */
	public List<Map<String,String>> queryListByType(String cType,String foreingKey,String permType) throws Exception{
		List list = null;
		if(StringUtils.isNotBlank(cType) && StringUtils.isNotBlank(foreingKey)&&StringUtils.isNotBlank(permType)){
			list = permissionMapper.queryListByType(cType, foreingKey,permType);
		}
		return list;
	}

	/**
	 * @see PermissionService#relatPerm(String, String, String, String)
	 * @param cType
	 * @param foreingKey
	 * @param relatCheckedCode
	 * @return
	 * @throws Exception
	 */
	public int relatPerm(String cType,String foreingKey,String relatCheckedCode,String permType) throws Exception{
		permissionMapper.deletePermRelat(cType, foreingKey,permType);
		if (StringUtils.isNotBlank(relatCheckedCode)){
			String[] codes = relatCheckedCode.split(",");
			if (codes!=null && codes.length>0){
				List<Map<String,String>> list = new ArrayList<>();
				Map<String,String> map = null;
				for (int i=0;i<codes.length;i++){
					map = new HashMap<>();
					map.put("pk",TemplateUtil.genUUID());
					map.put("permCode",codes[i]);
					map.put("cType",cType);
					map.put("foreingKey",foreingKey);
					map.put("permType",StringUtils.isNotBlank(permType)&& (StringUtils.equalsIgnoreCase(permType,"1") ||StringUtils.equalsIgnoreCase(permType,"0"))?permType.trim():null);
					list.add(map);
				}

				return permissionMapper.batchInsertPermRelat(list);
			}
		}
		return 0;
	}

}
